#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QHostAddress>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setWindowTitle("TCP - 服务器");
    ui->port->setText("8989");
    m_server = new QTcpServer(this);

    connect(m_server, &QTcpServer::newConnection, this, [=]()
    {
        m_tcp = m_server->nextPendingConnection();
        ui->record->append("成功和客户端建立了新的连接...");
        m_status->setPixmap(QPixmap(":/connect.png").scaled(20, 20));
        connect(m_tcp, &QTcpSocket::readyRead, this, [=]()
        {
            // 接收数据
            QString recvMsg = m_tcp->readAll();
            string msg = m_interface->decryptString(recvMsg.toStdString());
            ui->record->append("客户端Say: " + QString::fromStdString(msg));
        });
        connect(m_tcp, &QTcpSocket::disconnected, this, [=]()
        {
            ui->record->append("客户端已经断开了连接...");
            m_tcp->deleteLater();
            m_status->setPixmap(QPixmap(":/disconnect.png").scaled(20, 20));
        });
    });

    m_status = new QLabel;
    m_status->setPixmap(QPixmap(":/disconnect.png").scaled(20, 20));
    m_interface = new Interface;
    ui->statusBar->addWidget(new QLabel("连接状态: "));
    ui->statusBar->addWidget(m_status);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_startServer_clicked()
{
    unsigned short port = ui->port->text().toInt();
    m_server->listen(QHostAddress::Any, port);
    ui->startServer->setEnabled(false);
}

void MainWindow::on_sendMsg_clicked()
{
    QString sendMsg = ui->msg->toPlainText();
    string msg = m_interface->encryptString(sendMsg.toStdString());
    m_tcp->write(msg.data());
    ui->record->append("服务器Say: " + sendMsg);
    ui->msg->clear();
}
